//
//  SMHomeView.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/4.
//】

import SwiftUI
import SwiftUIIntrospect

struct SMHomeView: View {
    @StateObject private var viewModel = SMHomeViewModel()
    @State private var isPresented = false
    @Environment(\.navigationManager) var navManager
    @StateObject private var refreshController = SMScrollViewRefreshController()
    
    let banners = [
        SMBanner(
            id: 1,
            title: "新品上市",
            subtitle: "iPhone 15 系列震撼来袭",
            backgroundColor: .red,
            backgroundImageName: "home_customer_cycle"
        ),
        SMBanner(
            id: 2,
            title: "限时优惠",
            subtitle: "最高立减 ¥1000",
            backgroundColor: .green,
            backgroundImageName: "home_tips_cycle"
        )
    ]

    var body: some View {
        let baseConfig = SMBaseConfig(
            backgroundColor: .clear,
            showNavigationBar: false,
            hiddenTabbar: false
        )
        let navigationConfig = NavigationConfig(
            title: "Home",
            showSystemBackButton: false
        )

        
        SMBaseContentView(
            baseConfig: baseConfig,
            navigationConfig: navigationConfig
        ) {
            ZStack {
                // 背景图片放在最底层
                backgroundImage
                bottomBackgroundImage
                
                SMRefreshableScrollView(
                    refreshController: refreshController,
                    onRefresh: {
                        viewModel.loadHomeData()
                    }
                ) {
                    // 内容放在上层
                    ScrollView {
                        VStack(spacing: 20) {
                            // 顶部视图始终显示
                            SMHomeTopView(viewModel: viewModel,
                                          isLoading: viewModel.isLoading,
                                          onTapClosure: { model in
                                
                                print(model)
                                
                            })
                            .padding(.horizontal, 16)
                            
                            // 如果有 smallCardModel 数据，显示列表样式
    //                            if let smallCardModel = viewModel.smallCardModel,
    //                               !viewModel.isLoading {
                                let receiver = Receiveer.init(obsless: "ces", product_url: "ces", caulithoughose: 1, cipitfication: "ces", nuchfication: "ces", mechan: "ces", descript: "ces", product_type: "ces", rheier: "ces", is_copy_phone: "ces", patientable: 1, argue: "ces", juxtaette: "ces", menaciability: "ces", auctproof: "ces", passerency: "ces", billionuous: "ces", sufferice: "ces", meial: "ces", hortatbecomeule: "ces", dexter: "ces", riseize: "ces", interestdom: "ces", motherling: "ces", vulnerness: "ces", forer: ["ces"], palliten: "ces", umbrweapon: "ces", hold: "ces", easyish: 1, hortatant: "ces", hygrwhy: 1, but: "ces", oiditious: 1, aviarium: ["ces"], kinoacle: "ces", pletwise: nil, haloator: 1, returnaneity: "ces")
                                let smallModel = Septenier(storyitious: "text",
                                                                receiveer: [receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver,
                                                                            receiver])
                                SmallCardListView(smallCardModel: smallModel)
                                    .padding(.horizontal, 16)
                            
                            
    //                            // 只有有 largeCardModel 数据时才显示图片
//                            if let _ = viewModel.largeCardModel,
//                               !viewModel.isLoading {
//                                Image("choose_us")
//                                    .resizable()
//                                    .scaledToFill()
//                                    .padding(.horizontal, 16)
//                                
//                                Image("quick_loan_steps")
//                                    .resizable()
//                                    .scaledToFill()
//                                    .padding(.horizontal, 16)
//                                
//                                // 轮播视图
//                                SMInfiniteCarouselView(
//                                    banners,
//                                    autoScrollInterval: 3.0,
//                                    showsIndicators: false
//                                ) { banner in
//                                    SMBannerView(banner: banner)
//                                } onItemTapped: { banner in
//                                    print("点击轮播图：\(banner.title)")
//                                }
//                                .padding(.horizontal, 16)
//                                .frame(height: getImageHeight(
//                                    imageName: "home_customer_cycle",
//                                    targetWidth: kScreenWidth - 2 * 16
//                                ))
//                            }
                        }
                        .frame(maxHeight: .infinity)
                        .padding(.bottom, 5)
                    }
                    .padding(.bottom, 2)
                }
                
                Button("push") {
                    navManager.wrappedValue.pushView(tag: mainNav) {
                        ContentView()
                    }
                }
                .padding(EdgeInsets(top: 7, leading: 10, bottom: 7, trailing: 10))
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(8)
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) // ← 关键！
                .contentShape(Rectangle())

            }
        }
        .onAppear {
            if viewModel.homeListData == nil {
                refreshController.beginRefreshing()
            }
        }
        .onChange(of: viewModel.isLoading) { isLoading in
            // 使用 SMProgressHUD 管理类控制显示/隐藏
            if isLoading {
                SMProgressHUD.show("加载中...")
            } else {
                SMProgressHUD.dismiss()
                refreshController.endRefreshing()
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .checkAuthProgressNotification)) { notification in
            navManager.wrappedValue.pushTitleView(tag: mainNav) {
                SMIDAuthenticationView()
            }
        }
    }
    
    private var backgroundImage: some View {
        GeometryReader { geometry in
            Image("home_bgImage")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: geometry.size.width)
                .aspectRatio(1.0 / 0.7, contentMode: .fill)
                .frame(width: geometry.size.width, alignment: .top)
                .clipped()
        }
        .edgesIgnoringSafeArea(.all)
    }
    
    private var bottomBackgroundImage: some View {
        GeometryReader { geometry in
            Image("home_bottom_bg")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: geometry.size.width)
                .offset(y: 267)
        }
        .edgesIgnoringSafeArea(.all)
    }
}

struct SmallCardListView: View {
    let smallCardModel: Septenier
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // 列表内容
            LazyVStack(spacing: 20) {
                ForEach(Array(smallCardModel.receiveer.enumerated()), id: \.offset) { index, receiveer in
                    SmallCardRow(receiveer: receiveer, isLast: index == smallCardModel.receiveer.count - 1)
                        .onTapGesture {
                            print("index: \(index), receiveer: \(receiveer)")
                        }
                }
            }
            .background(Color.clear)
        }
    }
}

// 新增：SmallCard 列表行视图
struct SmallCardRow: View {
    let receiveer: Receiveer
    let isLast: Bool
    @State private var imageSize: CGSize = .zero
    
    var body: some View {
        
        ZStack {
            backgroundImage
            VStack(alignment: .leading, spacing: 8) {
                HStack {
                    // 主要信息
                    VStack(alignment: .leading, spacing: 4) {
                        if let title = receiveer.argue {
                            Text(title)
                                .font(.body)
                                .fontWeight(.medium)
                        }
                        
                        if let description = receiveer.passerency {
                            Text(description)
                                .font(.caption)
                                .foregroundColor(.gray)
                        }
                    }
                    
                    Spacer()
                    
                    // 右侧信息
                    VStack(alignment: .trailing, spacing: 4) {
                        if let amount = receiveer.auctproof {
                            Text("金额: \(amount)")
                                .font(.subheadline)
                                .foregroundColor(.primary)
                        }
                        
                        if let rate = receiveer.dexter {
                            Text("利率: \(rate)")
                                .font(.caption)
                                .foregroundColor(.red)
                        }
                    }
                }
                
                // 底部信息
                if let bottomText = receiveer.menaciability {
                    Text(bottomText)
                        .font(.caption2)
                        .foregroundColor(.gray)
                }
            }
            .padding(.horizontal, 10)
            .padding(.vertical, 0)
//            .frame(height: imageSize.height > 0 ? imageSize.height : 80)
            .frame(maxHeight: .infinity)
            .background(Color.clear)
            .cornerRadius(12)
        }
    }
    
    private var backgroundImage: some View {
        Image("product_cell_bg")
            .resizable()
            .scaledToFit()
    }
    
//    private var backgroundImage: some View {
//        Image("product_cell_bg")
//            .resizable()
//            .scaledToFill()
//            .background(
//                GeometryReader { imageGeometry in
//                    Color.clear
//                        .onAppear {
//                            // 获取图片的原始尺寸
//                            self.imageSize = imageGeometry.size
//                        }
//                        .onChange(of: imageGeometry.size) { newSize in
//                            // 如果尺寸变化，更新状态
//                            self.imageSize = newSize
//                        }
//                }
//            )
//    }
}


